/*
 * Copyright (c) 2006, 2022, webrx.cn All rights reserved.
 *
 */
package cn.webrx.utils;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.SignatureVerificationException;
import com.auth0.jwt.exceptions.TokenExpiredException;
import com.auth0.jwt.interfaces.Claim;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>Project: smvc2022 - JwtUtils
 * <p>Powered by webrx On 2022-04-07 16:33:59
 * <p>Created by IntelliJ IDEA
 *
 * @author webrx [webrx@126.com]
 * @version 1.0
 * @since 17
 */
public class JwtUtils {
    private String sign = "webrx2022";

    public JwtUtils(String sign) {
        this.sign = sign;
    }

    public JwtUtils() {

    }

    public String getSign() {
        return sign;
    }

    public void setSign(String sign) {
        this.sign = sign;
    }

    public String getToken(Map<String, String> payload, int minutes) {
        Calendar c = Calendar.getInstance();
        c.add(Calendar.MINUTE, minutes);
        JWTCreator.Builder builder = JWT.create();
        if (payload != null) payload.forEach(builder::withClaim);
        String token = builder.withExpiresAt(c.getTime()).sign(Algorithm.HMAC256(sign));
        return token;
    }

    public Map<String, String> getPayLoad(String token) {
        Map<String, String> map = new HashMap<>();
        if (verifyToken(token)) {
            JWTVerifier jv = JWT.require(Algorithm.HMAC256(sign)).build();
            try {
                //只要没有异常，就是信息是正确的。
                DecodedJWT dv = jv.verify(token);
                Map<String, Claim> mc = dv.getClaims();
                for (String k : mc.keySet()) {
                    map.put(k, k.equalsIgnoreCase("exp") ? String.format("%tF %<tT",mc.get(k).asDate()) : mc.get(k).asString());
                }

            } catch (Exception e) {
            }
        }

        return map;
    }

    public boolean verifyToken(String token) {
        boolean flag = false;
        JWTVerifier jv = JWT.require(Algorithm.HMAC256(sign)).build();
        try {
            //只要没有异常，就是信息是正确的。
            DecodedJWT dv = jv.verify(token);
            flag = true;
        } catch (TokenExpiredException tee) {
            //System.out.println("令牌过期");
        } catch (SignatureVerificationException sve) {
            //System.out.println("令牌异常，被篡改");
        } catch (Exception e) {
            //System.out.println("令牌异常");
        }
        return flag;
    }
}
